package com.atguigu.crowd.mvc.controller;

import com.atguigu.crowd.constant.CrowdConstant;
import com.atguigu.crowd.service.api.MenuService;
import com.atguigu.crowd.until.ResultEntity;
import crowd.entity.Menu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
public class MenuController {

    @Autowired
    private MenuService menuService;

    @RequestMapping("/menu/remove.json")
    public ResultEntity<String> removeMenuNode(@RequestParam("id") Integer id){

        menuService.removeMenuNode(id);

        return ResultEntity.successWithoutData();
    }


    /**
     * 更新节点数据
     * @param menu
     * @return
     */
    @RequestMapping("/menu/update.json")
    public ResultEntity<String> updateMenu(Menu menu){

        menuService.updateMenu(menu);

        return ResultEntity.successWithoutData();

    }


    /**
     * 添加子节点
     * @param menu
     * @return
     */
    @RequestMapping("/menu/save.json")
    public ResultEntity<String> saveMenu(Menu menu){

        // 如果模态框里有空值，则直接return
        if ((menu.getName() == null || menu.getName().length() == 0) ||
                (menu.getUrl() == null || menu.getUrl().length() == 0) ||
                (menu.getIcon() == null || menu.getIcon().length() == 0)){

            return new ResultEntity(ResultEntity.FAILED, CrowdConstant.MESSAGE_TEXT_BOX_IS_NULL, null);
        }

        menuService.saveMenu(menu);

        return ResultEntity.successWithoutData();

    }

    /**
     * 获取数据库中的全部菜单对象
     * @return
     */
    @RequestMapping("/menu/get/whole/tree.json")
    public ResultEntity<Menu> getWholeTree(){

        // 查询全部menu对象
        List<Menu> menuList = menuService.getAll();

        Map<Integer, Menu> menuMap = new HashMap<>();

        Menu root = null;


        // 遍历所有menu对象
        for (Menu menu : menuList) {

            // 获取对应的pid
            Integer id = menu.getId();
            // 将所有menu对象存入map集合中
            menuMap.put(id, menu);

        }

        for (Menu menu : menuList) {

            Integer pid = menu.getPid();

            // 根节点直接保存，跳过此次循环
            if (pid == null){

                root = menu;
                continue;

            }

            // 通过pid得到对应的父节点id
            Menu menuFather = menuMap.get(pid);
            // 存入父节点的children
            menuFather.getChildren().add(menu);

        }

        // 将根节点返回给客户端
        return ResultEntity.successWithData(root);
    }

}
